#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
用户管理标签页 - 包含获取当前用户和注册用户功能
"""

import requests
from PySide6.QtCore import Qt
from PySide6.QtGui import QPixmap, QImage
from PySide6.QtWidgets import (
    QWidget, QVBoxLayout, QFormLayout, QLineEdit,
    QPushButton, QLabel, QTextEdit, QGroupBox, QHBoxLayout
)

from src.ui.base_window import BaseWindow


class UserManagementTab(BaseWindow):
    """用户管理标签页"""
    
    def __init__(self, client):
        super().__init__()
        self.client = client
        self.admin_token_edit = None
        self.reg_username_edit = None
        self.reg_email_edit = None
        self.reg_password_edit = None
        self.user_info_display = None  # 用户信息展示区域
        
    def build_ui(self) -> QWidget:
        """构建UI界面"""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        
        # 当前用户信息组
        current_user_group = self._create_current_user_group()
        layout.addWidget(current_user_group)
        
        # 注册用户组（仅测试环境）
        register_group = self._create_register_user_group()
        layout.addWidget(register_group)
        
        # 结果输出区域
        layout.addWidget(QLabel("结果输出："))
        self.result_view = self.create_result_view()
        layout.addWidget(self.result_view)
        
        layout.addStretch()
        return widget
        
    def _create_current_user_group(self) -> QGroupBox:
        """创建当前用户信息组"""
        group = QGroupBox("获取当前用户信息")
        group.setStyleSheet("""
            QGroupBox {
                border: 1px solid #ccc;
                border-radius: 5px;
                padding: 10px;
                margin: 5px;
                font-weight: bold;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 10px;
                padding: 0 5px 0 5px;
            }
        """)
        
        layout = QVBoxLayout(group)
        
        # 获取当前用户信息按钮
        btn_me = QPushButton("获取当前用户信息")
        btn_me.clicked.connect(self.on_get_me)
        btn_me.setStyleSheet("""
            QPushButton {
                background-color: #9C27B0;
                color: white;
                padding: 8px 20px;
                border: none;
                border-radius: 3px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #7B1FA2;
            }
        """)
        layout.addWidget(btn_me, alignment=Qt.AlignmentFlag.AlignLeft)
        
        # 用户信息展示区域
        user_info_container = QWidget()
        user_info_layout = QHBoxLayout(user_info_container)
        
        # 头像显示区域
        self.avatar_label = QLabel()
        self.avatar_label.setFixedSize(80, 80)
        self.avatar_label.setStyleSheet("""
            QLabel {
                border: 2px solid #e9ecef;
                border-radius: 40px;
                background-color: #f8f9fa;
            }
        """)
        self.avatar_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.avatar_label.setText("头像")
        user_info_layout.addWidget(self.avatar_label)
        
        # 用户信息文本区域
        self.user_info_display = QTextEdit()
        self.user_info_display.setReadOnly(True)
        self.user_info_display.setMaximumHeight(100)
        self.user_info_display.setPlaceholderText("用户信息将在这里显示...")
        self.user_info_display.setStyleSheet("""
            QTextEdit {
                background-color: #f8f9fa;
                border: 1px solid #e9ecef;
                border-radius: 4px;
                padding: 8px;
                font-family: 'Courier New', monospace;
                font-size: 12px;
                color: #495057;
            }
        """)
        user_info_layout.addWidget(self.user_info_display)
        user_info_layout.setStretch(1, 1)  # 让文本区域占更多空间
        
        layout.addWidget(QLabel("用户信息："))
        layout.addWidget(user_info_container)
        
        return group
        
    def _create_register_user_group(self) -> QGroupBox:
        """创建注册用户组"""
        group = QGroupBox("注册用户（仅测试环境）")
        group.setStyleSheet("""
            QGroupBox {
                border: 1px solid #ccc;
                border-radius: 5px;
                padding: 10px;
                margin: 5px;
                font-weight: bold;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 10px;
                padding: 0 5px 0 5px;
            }
        """)
        
        layout = QVBoxLayout(group)
        
        # 警告提示
        tip = QLabel("⚠️ 仅用于测试环境：使用具有管理员权限的 Token 创建用户")
        tip.setStyleSheet("color:#d32f2f; font-weight: bold;")
        layout.addWidget(tip)
        
        # 注册表单
        form_layout = QFormLayout()
        
        self.admin_token_edit = QLineEdit()
        self.admin_token_edit.setPlaceholderText("管理员 JWT Token（可先用管理员账号登录复制过来）")
        form_layout.addRow("管理员 Token：", self.admin_token_edit)
        
        self.reg_username_edit = QLineEdit()
        self.reg_username_edit.setPlaceholderText("新用户名")
        form_layout.addRow("新用户名：", self.reg_username_edit)
        
        self.reg_email_edit = QLineEdit()
        self.reg_email_edit.setPlaceholderText("新邮箱地址")
        form_layout.addRow("新邮箱：", self.reg_email_edit)
        
        self.reg_password_edit = QLineEdit()
        self.reg_password_edit.setEchoMode(QLineEdit.EchoMode.Password)
        self.reg_password_edit.setPlaceholderText("新密码")
        form_layout.addRow("新密码：", self.reg_password_edit)
        
        layout.addLayout(form_layout)
        
        # 创建用户按钮
        btn_create = QPushButton("创建用户")
        btn_create.clicked.connect(self.on_create_user)
        btn_create.setStyleSheet("""
            QPushButton {
                background-color: #F44336;
                color: white;
                padding: 8px 20px;
                border: none;
                border-radius: 3px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #d32f2f;
            }
        """)
        layout.addWidget(btn_create, alignment=Qt.AlignmentFlag.AlignLeft)
        
        return group
        
    def on_get_me(self):
        """获取当前用户信息"""
        print("开始获取当前用户信息...")
        if not self.client.base_url:
            print("错误：未配置站点地址")
            self.show_warning("未配置站点地址", "请先在'站点设置'中保存 WordPress 站点地址")
            return
            
        print(f"请求站点: {self.client.base_url}")
        ok, data = self.client.get_current_user()
        print(f"获取用户信息结果: ok={ok}, data类型={type(data)}")
        if data:
            print(f"响应数据预览: {str(data)[:200]}...")
        
        # 在UI上显示用户信息
        if ok and data and 'data' in data:
            user_data = data['data']
            print(f"用户数据: {user_data}")
            user_info_text = self.format_user_info(user_data)
            self.user_info_display.setPlainText(user_info_text)
            print("用户信息显示成功")
        else:
            print("获取用户信息失败或数据格式错误")
            self.user_info_display.setPlainText("获取用户信息失败")
            self.avatar_label.setText("头像")  # 重置头像显示
        
        # 同时在结果输出区域显示原始数据
        self.print_result("当前用户信息", data)
        
    def format_user_info(self, user_data):
        """格式化用户信息用于显示"""
        info_parts = []
        
        # 基本信息
        if 'id' in user_data:
            info_parts.append(f"用户ID: {user_data['id']}")
        if 'name' in user_data:
            info_parts.append(f"用户名: {user_data['name']}")
        if 'slug' in user_data:
            info_parts.append(f"用户别名: {user_data['slug']}")
        if 'url' in user_data:
            info_parts.append(f"网站: {user_data['url']}")
        if 'description' in user_data and user_data['description']:
            info_parts.append(f"简介: {user_data['description']}")
        if 'link' in user_data:
            info_parts.append(f"用户链接: {user_data['link']}")
        
        # 加载头像
        if 'avatar_urls' in user_data:
            avatar_urls = user_data['avatar_urls']
            # 获取96px的头像，如果没有就用最大的那个
            avatar_url = avatar_urls.get('96', '')
            if not avatar_url:
                # 如果没有96px的，用最大的那个
                max_size = max([int(size) for size in avatar_urls.keys() if size.isdigit()], default=0)
                avatar_url = avatar_urls.get(str(max_size), '') if max_size else ''
            
            if avatar_url:
                self.load_avatar(avatar_url)
        
        # 链接信息
        if '_links' in user_data:
            links = user_data['_links']
            if 'self' in links and links['self']:
                self_link = links['self'][0].get('href', '')
                if self_link:
                    info_parts.append(f"API链接: {self_link}")
        
        return '\n'.join(info_parts) if info_parts else "暂无用户信息"
    
    def load_avatar(self, avatar_url):
        """加载用户头像"""
        print(f"开始加载头像: {avatar_url}")
        try:
            response = requests.get(avatar_url, timeout=10)
            print(f"头像请求状态码: {response.status_code}")
            if response.status_code == 200:
                image_data = response.content
                print(f"头像数据大小: {len(image_data)} 字节")
                image = QImage.fromData(image_data)
                print(f"图片加载成功: {not image.isNull()}")
                if not image.isNull():
                    # 缩放图片到合适大小并保持比例
                    scaled_image = image.scaled(80, 80, Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation)
                    pixmap = QPixmap.fromImage(scaled_image)
                    self.avatar_label.setPixmap(pixmap)
                    self.avatar_label.setText("")  # 清除占位文字
                    print("头像显示成功")
                else:
                    self.avatar_label.setText("头像")
                    self.show_warning("头像加载失败", "头像图片格式不正确或已损坏")
                    print("头像图片格式错误")
            else:
                self.avatar_label.setText("头像")
                self.show_warning("头像加载失败", f"服务器返回错误代码: {response.status_code}")
                print(f"服务器错误: {response.status_code}")
        except requests.exceptions.Timeout:
            self.avatar_label.setText("头像")
            self.show_warning("头像加载失败", "连接超时，请检查网络连接")
            print("头像加载超时")
        except requests.exceptions.ConnectionError:
            self.avatar_label.setText("头像")
            self.show_warning("头像加载失败", "网络连接失败，请检查网络设置")
            print("网络连接错误")
        except Exception as e:
            self.avatar_label.setText("头像")
            self.show_warning("头像加载失败", f"加载头像时出现错误: {str(e)}")
            print(f"加载头像失败: {e}")
    
    def on_create_user(self):
        """创建用户"""
        if not self.client.base_url:
            self.show_warning("未配置站点地址", "请先在“站点设置”中保存 WordPress 站点地址")
            return
            
        # 验证必填字段
        fields = {
            'admin_token': self.admin_token_edit,
            'username': self.reg_username_edit,
            'email': self.reg_email_edit,
            'password': self.reg_password_edit
        }
        field_names = {
            'admin_token': '管理员 Token',
            'username': '新用户名',
            'email': '新邮箱',
            'password': '新密码'
        }
        
        if not self.validate_required_fields(fields, field_names):
            return
            
        admin_token = self.admin_token_edit.text().strip()
        new_username = self.reg_username_edit.text().strip()
        new_email = self.reg_email_edit.text().strip()
        new_password = self.reg_password_edit.text()
        
        ok, data = self.client.create_user(admin_token, {
            "username": new_username,
            "email": new_email,
            "password": new_password,
            "roles": ["subscriber"]
        })
        
        self.print_result("创建用户", data)
        if ok:
            self.show_message("成功", "用户已创建（测试环境）")
            # 清空表单
            self.reg_username_edit.clear()
            self.reg_email_edit.clear()
            self.reg_password_edit.clear()
        else:
            self.show_warning("失败", "用户创建失败，请查看结果输出")